<script setup lang="tsx">
import AgvStatus from '@/views/agv-status.vue'
import Background from '@/views/background.vue'
import LogDrawer from '@/views/log-drawer.vue'
import RemoteDialog from '@/views/remote-dialog.vue'
import TaskDrawer from '@/views/task-drawer.vue'
import TaskStatus from '@/views/task-status.vue'
import LifterStatus from '@/views/lifter-status.vue'
import DoorStatus from '@/views/door-status.vue'
import dayjs from 'dayjs'
import { ref, watch } from 'vue'
import utc from 'dayjs/plugin/utc'
import timezone from 'dayjs/plugin/timezone'
import { useIntervalFn } from '@vueuse/core'
import { useLoadingStore } from '@/store/loading'
import { instance } from './utils/request'
import { ElNotification } from 'element-plus'

const loc = import.meta.env.VITE_LOC

const loadingStore = useLoadingStore()

const { toggleLoading } = loadingStore

dayjs.extend(utc)
dayjs.extend(timezone)

const currentTime = ref()

useIntervalFn(
  () => {
    currentTime.value = dayjs().tz('Asia/Shanghai').format('YYYY 年 MM 月 DD 日 HH:mm:ss')
  },
  1000,
  { immediateCallback: true },
)

const fullscreen = ref(false)

watch(fullscreen, (val) => {
  val ? document.documentElement.requestFullscreen() : document.exitFullscreen()
})

const logDrawerVisible = ref(false)

const remoteDialogVisible = ref(false)

const taskDrawerVisible = ref(false)

const reload = () => location.reload()

const isOnline = ref(true)

const getOnlineStatus = async () => {
  const { data } = await instance({
    url: `/remote/v1/agv/getLineStatus`,
    method: 'get',
  })
  isOnline.value = data === 0 ? false : true
}

if (loc === '375') {
  getOnlineStatus()
}

const switchOnlineStatus = async () => {
  try {
    toggleLoading(true)
    await instance({
      url: `/remote/v1/agv/lineStatus`,
      method: 'get',
      params: {
        id: isOnline.value ? 1 : 0,
      },
    })
    ElNotification({ type: 'success', title: '模式切换成功' })
    toggleLoading(false)
  } catch (error) {
    toggleLoading(false)
  }
}

const ws = new WebSocket('ws://192.168.1.100:8080/websocket')

ws.onopen = () => {
  ElNotification({ type: 'success', title: '服务器连接成功', duration: 1000 })
}

ws.onmessage = (event) => {
  const { level, message } = JSON.parse(event.data)
  if (level === 'error') {
    ElNotification({ type: 'error', title: '异常告警', message, duration: 0 })
  }
  if (level === 'warn') {
    ElNotification({
      type: 'warning',
      title: '系统提示',
      message,
      duration: 0,
      onClose: () => {
        ws.send('CLOSE')
      },
    })
  }
}

ws.onclose = () => {
  ElNotification({ type: 'error', title: '服务器断开连接', duration: 1000 })
}
</script>

<template>
  <div class="h-full max-h-full flex flex-col overflow-hidden" :class="[isOnline ? '' : 'filter opacity-40']">
    <div
      id="header-menu"
      class="h-24 min-h-24 pb-4 text-#67c6ff select-none"
      bg="no-repeat cover center-bottom"
      flex="~ justify-between items-center"
    >
      <div class="w-1/3 text-center font-normal whitespace-nowrap overflow-hidden text-ellipsis">
        <div class="flex items-center justify-center">
          <i class="i-icons:clock" />
          <span class="ml-1">{{ currentTime }}</span>
        </div>
      </div>
      <!-- <img class="w-56" src="@/assets/images/logo.png" /> -->
      <div
        class="flex items-center title-font text-2.5rem tracking-1 bg-clip-text text-transparent bg-gradient-to-b from-white to-gray"
      >
        {{ loc === '375' ? '溶剂转运系统' : '防爆类自动转运平台' }}
      </div>
      <div class="w-1/3 flex justify-center items-center">
        <ElSpace size="large" class="text-20px">
          <ElTooltip content="异常通知">
            <div class="i-icons:notice" @click="logDrawerVisible = !logDrawerVisible" />
          </ElTooltip>
          <ElTooltip content="任务列表">
            <div class="i-icons:task" @click="taskDrawerVisible = !taskDrawerVisible" />
          </ElTooltip>
          <!-- <ElTooltip content="远程控制">
            <div class="i-icons:remote" @click="remoteDialogVisible = !remoteDialogVisible" />
          </ElTooltip> -->
          <ElTooltip content="刷新系统">
            <div class="i-icons:reload" @click="reload()" />
          </ElTooltip>
          <ElTooltip content="全屏模式">
            <div class="i-icons:fullscreen" @click="fullscreen = !fullscreen" />
          </ElTooltip>
          <ElTooltip content="切换模式">
            <ElSwitch
              v-model="isOnline"
              active-text="在线"
              inactive-text="离线"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              @change="switchOnlineStatus"
            ></ElSwitch>
          </ElTooltip>
        </ElSpace>
      </div>
      <LogDrawer v-model="logDrawerVisible" />
      <RemoteDialog v-model="remoteDialogVisible" />
      <TaskDrawer v-model="taskDrawerVisible" />
    </div>
    <div
      class="h-[calc(100%-6rem)] relative"
      v-loading.fullscreen="loadingStore.loading"
      element-loading-background="rgba(0, 0, 0, 0.6)"
      element-loading-text="等待响应中..."
    >
      <Background />
      <div class="top-4 absolute" :class="[loc === '375' ? 'right-129' : 'right-4']">
        <LifterStatus :liftID="6" />
      </div>
      <div v-if="loc === '375'" class="right-4 top-4 absolute">
        <LifterStatus :liftID="8" />
      </div>
      <div class="right-4 absolute" :class="[loc === '375' ? 'top-78' : 'top-86']">
        <DoorStatus />
      </div>
      <div class="left-90 bottom-4 absolute">
        <AgvStatus />
      </div>
      <div class="left-4 bottom-4 absolute">
        <TaskStatus />
      </div>
    </div>
  </div>
</template>
